package com.authine.cloudpivot.ext.Utils;


import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class AccountAuthorize {


    /**
     *
     */
    public static void main(String[] args) {
        AccountAuthorize obj = new AccountAuthorize();
//        obj.getVedioAuthorize("system","","WINPC_V1");
//        obj.testFirstAuthorize("system1","192.168.11.43","WINPC_V1");

        String FirstAuthorize = obj.testFirstAuthorize("system", "192.168.11.43:5443", "WINPC_V1");
        System.out.println(FirstAuthorize);
        JSONObject FirstAuthorizeObj = JSONObject.fromObject(FirstAuthorize);
        log.info("FirstAuthorizeObj:{}", FirstAuthorizeObj.toString());
        String realm = FirstAuthorizeObj.getString("realm");
        System.out.println(realm);
    }


    private String requestStr(String userName, String ipAddress, String clientType) {
//        StringBuffer sb=new StringBuffer();
//        sb.append("system=");
//        sb.append("web&");
//        sb.append("userName=");
//        sb.append(userName+"&");
//        sb.append("ipAddress=");
//        sb.append(ipAddress+"&");
//        sb.append("clientType=");
//        sb.append(clientType);

        //        return sb.toString();
        Map<String, String> map = new HashMap<String, String>();
        map.put("userName", userName);
        map.put("ipAddress", ipAddress);
        map.put("clientType", clientType);
        //需要引入阿里的fastJson包
        String result = JSON.toJSONString(map);
        System.out.println("result: " + result);
        return result;
    }

    /**
     * 第一次登陆
     *
     * @return
     */
    public static String testFirstAuthorize(String userName, String ipAddress, String clientType) {
        //初始化 restTemplate
        Map<String, String> map = new HashMap<String, String>();
        String result = JSON.toJSONString(map);
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(1 * 1000);
        requestFactory.setReadTimeout(30 * 1000);
        requestFactory.setOutputStreaming(false);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
//        String url = "http://192.168.11.43:82/admin/API/accounts/authorize";
        String url = "http://222.187.39.42:82/admin/API/accounts/authorize";

        Map<String, String> params = new HashMap<String, String>();
        params.put("userName", userName);
        params.put("ipAddress", ipAddress);
        params.put("clientType", clientType);
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json;charset=utf-8"));
        HttpEntity<Map<String, String>> request = new HttpEntity<Map<String, String>>(params, headers);
        try {
            String flag = restTemplate.postForObject(url, request, String.class);
            log.info("restTemplate.postForObject返回结果：{}", flag);
        } catch (RestClientException e) {
            if (e instanceof HttpClientErrorException) {
                HttpClientErrorException response = (HttpClientErrorException) e;
                log.info("response：{}", response);
                log.info("response.getStatusCode：{}", response.getStatusCode());
                if (401 == response.getStatusCode().value()) {
                    String body = response.getResponseBodyAsString();
                    result = body;
                    log.info("body: {}", body);
                } else {
                    e.printStackTrace();
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 第二次登陆
     */
    public static String testSecondAuthorize(String mac, String signature, String userName, String randomKey, String publicKey, String encryptType, String ipAddress, String clientType, String userType) {
        //初始化 restTemplate
        Map<String, String> map = new HashMap<String, String>();
        String result = JSON.toJSONString(map);
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(1 * 1000);
        requestFactory.setReadTimeout(30 * 1000);
        requestFactory.setOutputStreaming(false);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
//        String url = "http://192.168.11.43:82/admin/API/accounts/authorize";
        String url = "http://222.187.39.42:82/admin/API/accounts/authorize";
        Map<String, String> params = new HashMap<String, String>();
        params.put("mac", mac);
        params.put("signature", signature);
        params.put("userName", userName);
        params.put("randomKey", randomKey);
        params.put("publicKey", publicKey);
        params.put("encryptType", encryptType);
        params.put("ipAddress", ipAddress);
        params.put("clientType", clientType);
        params.put("userType", userType);
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json;charset=utf-8"));
        HttpEntity<Map<String, String>> request = new HttpEntity<Map<String, String>>(params, headers);
        try {
            String adhv = restTemplate.postForObject(url, request, String.class);
            result = adhv;
        } catch (RestClientException e) {
            if (e instanceof HttpClientErrorException) {
                HttpClientErrorException response = (HttpClientErrorException) e;
                if (401 == response.getStatusCode().value()) {
                    String body = response.getResponseBodyAsString();
                    result = body;
                    System.out.println("body: " + body);
                } else {
                    e.printStackTrace();
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 保持心跳
     */
    public static String KeepAlive(String Vediotoken, String duration) {
        //初始化 restTemplate
        Map<String, String> map = new HashMap<String, String>();
        String result = JSON.toJSONString(map);
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(1 * 1000);
        requestFactory.setReadTimeout(30 * 1000);
        requestFactory.setOutputStreaming(false);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        String url = "http://192.168.11.43/admin/API/accounts/keepalive?token=" + Vediotoken + " ";
        Map<String, String> params = new HashMap<String, String>();
        params.put("token", Vediotoken);
        params.put("duration", duration);

        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json;charset=utf-8"));
        HttpEntity<Map<String, String>> request = new HttpEntity<Map<String, String>>(params, headers);
        try {
            String a = "sucesss";
            restTemplate.put(url, request, String.class);
            String b = "sucesss";
            return a;

        } catch (RestClientException e) {


        } catch (Exception e) {
            e.printStackTrace();
        }
        return "sd";
    }


    /**
     * 添加角色
     */
    public static String AddRole(String token, String roleName, String menuNodeNames, String functionNames, String relDeviceCodes) {
        //初始化 restTemplate
        Map<String, String> map = new HashMap<String, String>();
        String result = JSON.toJSONString(map);
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(1 * 1000);
        requestFactory.setReadTimeout(30 * 1000);
        requestFactory.setOutputStreaming(false);
        JSONArray JsonArray1 = new JSONArray();
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        String url = "http://192.168.11.43/admin/API/Role/addRoles?token=" + token + "";
        Map<String, String> params = new HashMap<String, String>();
        JSONObject json = new JSONObject();
        try {
            json.put("roleName", roleName);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
//      try {
//		json.put("orgNodeName", null);
//	} catch (JSONException e1) {
//		// TODO Auto-generated catch block
//		e1.printStackTrace();
//	}
        try {
            json.put("menuNodeNames", menuNodeNames);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            json.put("functionNames", functionNames);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            json.put("relDeviceCodes", relDeviceCodes);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
//      try {
//		json.put("roleUserJson", JsonArray1);
//	} catch (JSONException e1) {
//		// TODO Auto-generated catch block
//		e1.printStackTrace();
//	}
//    params.put("roleName", roleName);
//    params.put("orgNodeName", orgNodeName);
//    params.put("menuNodeNames", menuNodeNames);
//    params.put("functionNames", functionNames);
//    params.put("roleUserJson", roleysereJson);

//      JSONObject Json = new JSONObject();
        JSONArray JsonArray = new JSONArray();
        JsonArray.add(json);
        System.out.println("jsonArray:" + JsonArray);


        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json;charset=utf-8"));

//      String resulto = restTemplate.postForObject(url, json, String.class);
        HttpEntity<Map<String, String>> request = new HttpEntity<Map<String, String>>(params, headers);
        try {
//          String adhv=restTemplate.postForObject(url, request, Stringclass);
            String adhv = restTemplate.postForObject(url, JsonArray, String.class);
            result = adhv;
        } catch (RestClientException e) {
            if (e instanceof HttpClientErrorException) {
                HttpClientErrorException response = (HttpClientErrorException) e;
                if (401 == response.getStatusCode().value()) {
                    String body = response.getResponseBodyAsString();
                    result = body;
                    System.out.println("body: " + body);
                } else {
                    e.printStackTrace();
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 添加角色
     */
    public static String UpdateRole(String token, String roleName, String menuNodeNames, String optFunctionNames, String relDeviceCodes) {
        //初始化 restTemplate
        Map<String, String> map = new HashMap<String, String>();
        String result = JSON.toJSONString(map);
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(1 * 1000);
        requestFactory.setReadTimeout(30 * 1000);
        requestFactory.setOutputStreaming(false);
        JSONArray JsonArray1 = new JSONArray();
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        String url = "http://192.168.11.43:82/admin/API/Role/updateRoles?token=" + token + "";
        Map<String, String> params = new HashMap<String, String>();
        JSONObject json = new JSONObject();
        try {
            json.put("roleName", roleName);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            json.put("menuNodeNames", menuNodeNames);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            json.put("optFunctionNames", optFunctionNames);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            json.put("relChannelNames", relDeviceCodes);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        JSONArray JsonArray = new JSONArray();
        JsonArray.add(json);
        System.out.println("jsonArray:" + JsonArray);


        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json;charset=utf-8"));

//      String resulto = restTemplate.postForObject(url, json, String.class);
        HttpEntity<Map<String, String>> request = new HttpEntity<Map<String, String>>(params, headers);
        try {
//          String adhv=restTemplate.postForObject(url, request, Stringclass);
            String adhv = restTemplate.postForObject(url, JsonArray, String.class);
            result = adhv;
        } catch (RestClientException e) {
            if (e instanceof HttpClientErrorException) {
                HttpClientErrorException response = (HttpClientErrorException) e;
                if (401 == response.getStatusCode().value()) {
                    String body = response.getResponseBodyAsString();
                    result = body;
                    System.out.println("body: " + body);
                } else {
                    e.printStackTrace();
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 添加人员到角色
     */
    public static String UpdateUser(String token, String loginName, String roleNames) {
        //初始化 restTemplate
        Map<String, String> map = new HashMap<String, String>();
        String result = JSON.toJSONString(map);
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(1 * 1000);
        requestFactory.setReadTimeout(30 * 1000);
        requestFactory.setOutputStreaming(false);
        JSONArray JsonArray1 = new JSONArray();
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        String url = "http://192.168.11.43:82/admin/API/user/updateUser?token=" + token + "";
        Map<String, String> params = new HashMap<String, String>();
        JSONObject json = new JSONObject();
        try {
            json.put("loginName", loginName);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            json.put("roleNames", roleNames);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        JSONArray JsonArray = new JSONArray();
        JsonArray.add(json);
        System.out.println("jsonArray:" + JsonArray);


        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json;charset=utf-8"));

//      String resulto = restTemplate.postForObject(url, json, String.class);
        HttpEntity<Map<String, String>> request = new HttpEntity<Map<String, String>>(params, headers);
        try {
//          String adhv=restTemplate.postForObject(url, request, Stringclass);
            String adhv = restTemplate.postForObject(url, JsonArray, String.class);
            result = adhv;
        } catch (RestClientException e) {
            if (e instanceof HttpClientErrorException) {
                HttpClientErrorException response = (HttpClientErrorException) e;
                if (401 == response.getStatusCode().value()) {
                    String body = response.getResponseBodyAsString();
                    result = body;
                    System.out.println("body: " + body);
                } else {
                    e.printStackTrace();
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 查询角色
     */
    public static String GetRoleId(String Vediotoken, String roleName) {
        //初始化 restTemplate
        Map<String, String> map = new HashMap<String, String>();
        String result = JSON.toJSONString(map);
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(1 * 1000);
        requestFactory.setReadTimeout(30 * 1000);
        requestFactory.setOutputStreaming(false);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        String url = "http://192.168.11.43/admin/API/Role/role?roleName=" + roleName + "&token=" + Vediotoken + " ";
        Map<String, String> params = new HashMap<String, String>();
        params.put("token", Vediotoken);
        params.put("roleName", roleName);

        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json;charset=utf-8"));
        HttpEntity<Map<String, String>> request = new HttpEntity<Map<String, String>>(params, headers);
        try {
            String a = "sucesss";
            restTemplate.put(url, request, String.class);
            String b = "sucesss";
            return a;

        } catch (RestClientException e) {


        } catch (Exception e) {
            e.printStackTrace();
        }
        return "sd";
    }


    /**
     * 查询角色权限
     */
    public static String GetRoleAuthId(String Vediotoken, String roleName) {
        //初始化 restTemplate
        Map<String, String> map = new HashMap<String, String>();
        String result = JSON.toJSONString(map);
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(1 * 1000);
        requestFactory.setReadTimeout(30 * 1000);
        requestFactory.setOutputStreaming(false);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        String url = "http://192.168.11.43/admin/API/Role/role?roleName=" + roleName + "&token=" + Vediotoken + " ";
        Map<String, String> params = new HashMap<String, String>();
        params.put("token", Vediotoken);
        params.put("roleName", roleName);

        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json;charset=utf-8"));
        HttpEntity<Map<String, String>> request = new HttpEntity<Map<String, String>>(params, headers);
        try {
            String a = "sucesss";
            restTemplate.put(url, request, String.class);
            String b = "sucesss";
            return a;

        } catch (RestClientException e) {


        } catch (Exception e) {
            e.printStackTrace();
        }
        return "sd";
    }


    public static JSONObject DevicesList(String token) {
        JSONObject json_test = null;
        //初始化 restTemplate
        Map<String, String> map = new HashMap<String, String>();
        String result = JSON.toJSONString(map);
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(1 * 1000);
        requestFactory.setReadTimeout(30 * 1000);
        requestFactory.setOutputStreaming(false);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        String url = "http://192.168.11.43/admin/API/tree/devices?token=" + token + "";
        Map<String, String> params = new HashMap<String, String>();
        params.put("orgCode", "");

        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json;charset=utf-8"));
        HttpEntity<Map<String, String>> request = new HttpEntity<Map<String, String>>(params, headers);
        try {
            String adhv = restTemplate.postForObject(url, request, String.class);
            json_test = JSONObject.fromObject(adhv);
            result = adhv;
            adhv = restTemplate.postForObject(url, request, String.class);
        } catch (RestClientException e) {
            if (e instanceof HttpClientErrorException) {
                HttpClientErrorException response = (HttpClientErrorException) e;
                if (401 == response.getStatusCode().value()) {
                    String body = response.getResponseBodyAsString();
                    result = body;
                    System.out.println("body: " + body);
                } else {
                    e.printStackTrace();
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json_test;
    }

    public static JSONObject getRoleAuth(String Vediotoken, String roleName) {
        JSONObject json_test = null;
        //初始化 restTemplate
        Map<String, String> map = new HashMap<String, String>();
        String result = JSON.toJSONString(map);
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(1 * 1000);
        requestFactory.setReadTimeout(30 * 1000);
        requestFactory.setOutputStreaming(false);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        String url = "http://192.168.11.43/admin/API/Role/role?roleName=" + roleName + "&token=" + Vediotoken + " ";
        Map<String, String> params = new HashMap<String, String>();
        params.put("orgCode", "");

        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json;charset=utf-8"));
        HttpEntity<Map<String, String>> request = new HttpEntity<Map<String, String>>(params, headers);
        try {
            String adhv = restTemplate.postForObject(url, request, String.class);
            json_test = JSONObject.fromObject(adhv);
            result = adhv;
            adhv = restTemplate.postForObject(url, request, String.class);
        } catch (RestClientException e) {
            if (e instanceof HttpClientErrorException) {
                HttpClientErrorException response = (HttpClientErrorException) e;
                if (401 == response.getStatusCode().value()) {
                    String body = response.getResponseBodyAsString();
                    result = body;
                    System.out.println("body: " + body);
                } else {
                    e.printStackTrace();
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json_test;
    }


    /**
     * 添加人员
     */
    public static String AddPerson(String loginName, String loginPass, String isReuse, String roleIds, String token) {
        //初始化 restTemplate
        Map<String, String> map = new HashMap<String, String>();
        String result = JSON.toJSONString(map);
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(1 * 1000);
        requestFactory.setReadTimeout(30 * 1000);
        requestFactory.setOutputStreaming(false);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        String url = "http://192.168.11.43/admin/API/user/batchAddUser?token='" + token + "' ";
        Map<String, String> params = new HashMap<String, String>();
        params.put("loginName", loginName);
        params.put("loginPass", loginPass);
        params.put("isReuse", isReuse);
        params.put("roleIds", roleIds);
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json;charset=utf-8"));
        HttpEntity<Map<String, String>> request = new HttpEntity<Map<String, String>>(params, headers);
        try {
            String adhv = restTemplate.postForObject(url, request, String.class);
            result = adhv;
        } catch (RestClientException e) {
            if (e instanceof HttpClientErrorException) {
                HttpClientErrorException response = (HttpClientErrorException) e;
                if (401 == response.getStatusCode().value()) {
                    String body = response.getResponseBodyAsString();
                    result = body;
                    System.out.println("body: " + body);
                } else {
                    e.printStackTrace();
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
